package com.ls.lsqc.modules.sys.web;

import com.ls.lsqc.modules.sys.utils.SystemMessageUtils;
import groovy.util.ResourceException;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.ls.lsqc.common.persistence.AjaxDone;
import com.ls.lsqc.common.persistence.BaseEntity;
import com.ls.lsqc.common.persistence.Page;
import com.ls.lsqc.common.utils.ResourcesUtil;
import com.ls.lsqc.common.utils.StringUtils;
import com.ls.lsqc.common.web.BaseController;
import com.ls.lsqc.modules.sys.entity.Dict;
import com.ls.lsqc.modules.sys.entity.Shop;
import com.ls.lsqc.modules.sys.entity.User;
import com.ls.lsqc.modules.sys.service.ShopService;
import com.ls.lsqc.modules.sys.service.SystemService;
import com.ls.lsqc.modules.sys.utils.DictUtils;
import com.ls.lsqc.modules.sys.utils.UserUtils;

/**
 * 店铺Controller
 * @author 
 * @version 2014-05-16
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/shop")
public class ShopController extends BaseController {

	@Autowired
	private ShopService shopService;
	
	@Autowired
	private SystemService systemService;
	
	
	// 取店铺信息
    @ModelAttribute
    public Shop get(@RequestParam(required=false) String id,HttpServletRequest request) {
        
        if (StringUtils.isNotBlank(id)){
            Shop shop=shopService.getShop(Long.parseLong(id));
            
            User user = systemService.getUser(Long.parseLong(shop.getContactPersonId()));
            
            shop.setUser(user);
            // 店铺管理人员设置版本号
            shop.getUser().setVersion(user.getVersion());
            return shop;
        }else{
            return new Shop();
        }
    }
    
	
	@RequiresPermissions("sys:shop:view")
	@RequestMapping(value = {"list", ""})
	public String list(Shop shop, HttpServletRequest request, HttpServletResponse response, Model model) {

		if(UserUtils.isShopUser()){
			
			shop.setId(UserUtils.getUser().getShop().getId());
		}
		
	    Page<Shop> page = shopService.findShop(new Page<Shop>(request, response), shop);
	    
	    model.addAttribute("page", page);
	    return "modules/sys/shopList";
	}
	
	/**
     * 进入编辑用户页面
     * @param shop
     * @param model
     * @return
     */
    @RequiresPermissions("sys:shop:edit")
    @RequestMapping(value = "form")
    public String form(Shop shop,HttpServletRequest request, Model model) {
        //选中城市信息
        List<Map<String,Object>> shopStyleSelectList=Lists.newArrayList();
        
        User user=new User();
       
        if(shop.getId()!=null){
            user=shop.getUser();
            shopStyleSelectList=shopService.findShopStyle(shop.getId().toString());
        }
        model.addAttribute("shop", shop);
        model.addAttribute("user",user );
        model.addAttribute("shopStyleSelectList", shopStyleSelectList);
        model.addAttribute("allRoles", systemService.findAllRole());
        return "modules/sys/shopEdit";
    }

    /**
     * 联动返回城市
     * @param code
     * @param model
     * @return
     */
    @RequiresPermissions("sys:shop:view")
    @RequestMapping(value = "city")
    @ResponseBody
    public String city(String code,Model model,HttpServletResponse response ) {
        
        List<Dict> cityList=DictUtils.getDictList(code);
        
        return renderString(response, cityList);
       
    }

    
    /**
     * 进入查看用户页面
     * @param shop
     * @param model
     * @return
     */
    @RequiresPermissions("sys:shop:view")
    @RequestMapping(value = "show")
    public String show(Shop shop, Model model,HttpServletRequest request) {
        // 店铺信息
    	//shop=get(shop.getId().toString(),request);

        // 店铺管理原信息
        List<Map<String,Object>> shopStyleSelectList=shopService.findShopStyle(shop.getId().toString());
        
        model.addAttribute("shop", shop);
        model.addAttribute("shopStyleSelectList", shopStyleSelectList);
        model.addAttribute("user",shop.getUser() );
        model.addAttribute("allRoles", systemService.findAllRole());
        
        return "modules/sys/shopShow";
    }


	private Shop extracted(Shop shop, HttpServletRequest request) {
		shop=get(shop.getId().toString(),request);
		return shop;
	}
    
    
    
    @RequiresPermissions("sys:shop:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(Shop shop, HttpServletRequest request, Model model, HttpServletResponse response ) throws ResourceException {
    	// 判断邮箱重复验证
    	if(shop.getUser().getId() != null&&systemService.checkEmailName(shop.getUser())!=null){
        	if(!shop.getUser().getId().toString().equals(systemService.checkEmailName(shop.getUser()).getId().toString())){
        		return renderString(response,AjaxDone.error(getText("user_emailExist")));
        	}
        }else{
        	if(systemService.checkEmailName(shop.getUser())!=null){
        		return renderString(response,AjaxDone.error(getText("user_emailExist")));
        	}
        }
    	
        if(shop.getId()!=null){
            
            //判断数据是否删除
            Shop shopNew=get(shop.getId().toString(),request);
            if(shopNew==null || BaseEntity.DEL_FLAG_DELETE.equals(shopNew.getDeleteFlag())){
                return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
            //店铺管理人员排他
            if(shop.getUser().getVersion()==systemService.getUser(Long.parseLong(shop.getContactPersonId())).getVersion()){
                shop.getUser().setVersion(shop.getUser().getVersion()+1);
            }else{
                return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
            
            //排他
            if(shop.getVersion()==get(shop.getId().toString(),request).getVersion()){
                shop.setVersion(shop.getVersion()+1);
            }else{
                return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
        }
        // 如果新密码为空，则不更换密码
        if (shop.getUser()!=null && StringUtils.isNotBlank(shop.getUser().getNewPassword())) {
            
            shop.getUser().setPassword(SystemService.entryptPassword(shop.getUser().getNewPassword()));
        }
         // 保存用户信息
         shopService.saveShopOrUser(shop);
        
        return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "shop_userSaveShop")));
   
    }
    
    @RequiresPermissions("sys:shop:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(Shop shop, HttpServletRequest request, Model model, HttpServletResponse response ) {
        
        if(shop.getId()!=null){
            
            if(shop.getVersion()==get(shop.getId().toString(),request).getVersion()){
                shop.setVersion(shop.getVersion()+1);
            }else{
                return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
        }
        
        try {
            // 保存用户信息
            shopService.deletShopOrUser(shop);
            
            return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "shop_delectShop")));
            
        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
            return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
        }
    }
    
    /**
     * 验证登录名是否有效
     * 
     * @param oldLoginName
     * @param shop
     * @return
     */
    @ResponseBody
    @RequiresPermissions("sys:shop:edit")
    @RequestMapping(value = "checkLoginName")
    public String checkLoginName(String oldLoginName, Shop shop) {
    	String loginName=shop.getUser().getLoginName();
        if (loginName != null && loginName.equals(oldLoginName)) {
            return "true";
        } else if (loginName != null&& systemService.getUserByLoginName(loginName) == null) {
            return "true";
        }
        return "false";
    }
    
    /**
     * 验证店铺名是否有效
     * 
     * @param oldShopName
     * @param shopName
     * @return
     */
    @ResponseBody
    @RequiresPermissions("sys:shop:edit")
    @RequestMapping(value = "checkShopName")
    public String checkShopName(String oldShopName, String shopName) {
        if (shopName != null && shopName.equals(oldShopName)) {
            return "true";
        } else if (shopName != null&& shopService.getShopByShopName(shopName) == null) {
            return "true";
        }
        return "false";
    }
    
}
